package edu.metrostate.capstonediner;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.app.AlertDialog;

public class Login extends Activity implements Runnable{
	private final int REQUEST_EXIT = 1;

    Button btnLoginT;
    private Login myInstance;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        myInstance = this;
        
        // Buttons
        btnLoginT = (Button) findViewById(R.id.btnloginNow);
        
        // Login with the username and password
        btnLoginT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	new Thread(myInstance).start();
            }
        });
        
        Button createAccountBTN = (Button) findViewById(R.id.btnCreateAccount);
        
        createAccountBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	Intent i = new Intent(getApplicationContext(), CreateAccountActivity.class);
            	startActivityForResult(i, REQUEST_EXIT);
            }
        });
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_EXIT) {
             if (resultCode == RESULT_OK) {
                this.finish();

             }
         }
    }
    
	@Override
	public void run() {
		String user = ((EditText)findViewById(R.id.inputUserName)).getText().toString();
    	String password = ((EditText)findViewById(R.id.inputPassword)).getText().toString();
    	
    	Looper.prepare();
    	AlertDialog.Builder builder = new AlertDialog.Builder(myInstance);

        // Starts the check for the name and password in database
    	if (DatabaseHTTP.ValidateUser(user, password)) {
    		GameActivity.setUser(user);
    		builder.setMessage("Hi " + user + "!  You are now logged in.");
    		builder.setPositiveButton("Okay!", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					myInstance.finish();
				}
			});
            builder.create().show();
            Looper.loop();
    	} else {
            builder.setMessage("Invalild Username and/or Password.");
            builder.create().show();
            Looper.loop();
    	}
	}
}
